import performance from "./performance/index";

import { setConfig } from "./config";

// 声明全局变量__monitorSDK__
declare global {
  interface Window {
    __monitorSDK__: {
      version: string;
      vue?: boolean;
      react?: boolean;
    };
  }
}

// 初始化__monitorSDK__对象
window.__monitorSDK__ = {
  version: '0.0.1'
};

function init(options:any){
    setConfig(options);
}

//Vue中错误监测
export function install(Vue: { config: { errorHandler?: (err: Error, vm: any, info: string) => void } }, options: any) {
  if (window.__monitorSDK__.vue) return;
  window.__monitorSDK__.vue = true;
  setConfig(options);
  const handler = Vue.config.errorHandler;

  Vue.config.errorHandler = function(err, vm, info){
    const reportData = {
      info,
      error: err.stack,
      subType: 'vue',
      type: 'error',
      startTime: window.performance.now(),
      pageURL: window.location.href,
    };
    // TODO: 上报错误

    if (handler) {
      handler.call(this, err, vm, info);
    }
  };
}

//针对React项目中的错误捕获

export function errorBoundary(err:any,info:any){
    if(window.__monitorSDK__.react)return;
    window.__monitorSDK__.react = true;

    const reportData = {
        error: err?.stack,
        info,
        subType: 'react',
        type: 'error',
        startTime: window.performance.now(),
        pageURL: window.location.href,
    };

}

export default{
    performance,
    init
}